//webSocket通用处理
import store from '../../store'
export const webSocketMixins = {
  data() {
    return {
      websock: null,
      lockReconnect:false,
      onSuccess:null
    }
  },
  props: {},

  methods: {
    initWebSocket: function (callback) {
      let url =this.api.websocket + '/' + store.getters.userId
      url = url.replace('https', 'ws').replace('http', 'ws')
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
      this.onSuccess=callback;
    },
    websocketOnopen: function () {
      console.log("WebSocket连接成功");
    },
    websocketOnerror: function (e) {
      console.log("WebSocket连接发生错误");
      this.reconnect();
    },
    websocketOnmessage: function (e) {
      console.log("-----接收消息-------", JSON.parse(e.data));
      let messageInfo = JSON.parse(event.data)
      this.onSuccess&&this.onSuccess(messageInfo);
    },
    websocketOnclose: function (e) {
      console.log("connection closed (" + e + ")");
      if (e) {
        console.log("connection closed (" + e.code + ")");
      }
      this.reconnect();
    },
    websocketSend(text) { // 数据发送
      try {
        this.websock.send(text);
      } catch (err) {
        console.log("send failed (" + err.code + ")");
      }
    },
    reconnect() {
      if (this.lockReconnect) return;
      this.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout( ()=> {
        console.info("尝试重连...");
        this.initWebSocket();
        this.lockReconnect = false;
      }, 5000);
    },
  }
}
